package com.nt.train.util.expands;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import java.util.Objects;
/**
 * https://blog.csdn.net/qq_45369589/article/details/123095028
 * Spring 的工具类，获取bean实例
 * @author hlf
 * @version 1.0
 * @date 2022/9/28 21:54
 */
@Slf4j
@Configuration
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * 通过bean的名字、类型获取bean实例
     * @param beanName bean在spring中的名字
     * @param clazz    bean的类型
     * @param <T>      实例的类型，通过clazz来确定
     * @return spring容器中的bean实例
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        return applicationContext.getBean(beanName, clazz);
    }

    /**
     * 通过bean的名字、类型获取bean实例
     * @param beanName bean在spring中的名字
     * @return spring容器中的bean实例
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    /**
     * 获取业务实现的 Bean。
     * @param prefix       前缀，没有时，可以为空字符串
     * @param beanName     bean名，其实是包+类名
     * @param businessType 业务类型, {@link BusinessType}中的常量；没有时，可以为空字符串
     * @return 对应的bean
     */
    public static Object getBusinessBean(@NonNull String prefix, @NonNull String beanName, @NonNull String businessType) {
        String beanKey = String.join("-", prefix, beanName, businessType);
        log.info("prefix={}，beanName={}，businessType={}", prefix, beanName, businessType);
        Object bean = CommonsUtil.BEANS.get(beanKey);
        if (Objects.isNull(bean)) {
            log.debug("参数错误：prefix={}，beanName={}，businessType={}", prefix, beanName, businessType);
            System.out.println("beanKey对应名称："+beanKey);
            throw new IllegalArgumentException("参数错误，无法找到对应的 Bean");
        }
        return bean;
    }

//    public static <T> TgetBusinessBeanByObj(@NonNull String prefix, @NonNull String beanName, @NonNull String businessType) {
//        String beanKey = String.join("-", prefix, beanName, businessType);
//        Object bean = CommonsUtil.BEANS.get(beanKey);
//        if (Objects.isNull(bean)) {
//            log.debug("参数错误：prefix={}，beanName={}，businessType={}", prefix, beanName, businessType);
//            System.out.println("beanKey对应名称："+beanKey);
//            throw new IllegalArgumentException("参数错误，无法找到对应的 Bean");
//        }
//        Class testClase = Class.forName(bean.toString());
//        return applicationContext.getBean(beanName, testClase);
//    }


}
